<template>
  <view class="login-container">
    <view class="logo-box">
      <image class="logo" src="/static/images/logo.png" mode="aspectFit"></image>
      <text class="app-name">微信小程序示例</text>
    </view>
    
    <view class="welcome-text">
      <text class="welcome-title">欢迎使用</text>
      <text class="welcome-desc">登录后体验更多功能</text>
    </view>
    
    <view class="login-box">
      <button class="login-btn" @click="handleLogin" :loading="loading">
        <text class="iconfont icon-wechat"></text>
        微信一键登录
      </button>
      
      <view class="agreement-box">
        <checkbox :checked="isAgree" @click="toggleAgreement" color="#07c160" />
        <text class="agreement-text">
          我已阅读并同意
          <text class="link" @click="goToAgreement('user')">《用户协议》</text>
          和
          <text class="link" @click="goToAgreement('privacy')">《隐私政策》</text>
        </text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import useAuth from '../../hooks/useAuth';
import { ROUTES, AGREEMENT_TYPES } from '../../constants';

// 声明uni类型
declare const uni: any;

// 是否同意协议
const isAgree = ref(false);

// 是否加载中
const loading = ref(false);

// 获取认证相关的方法
const { handleWxLogin } = useAuth();

// 存储来源页面路径
const fromPath = ref('');

// 切换协议同意状态
const toggleAgreement = () => {
  isAgree.value = !isAgree.value;
};

// 处理登录
const handleLogin = () => {
  // 检查是否同意协议
  if (!isAgree.value) {
    uni.showToast({
      title: '请先阅读并同意用户协议和隐私政策',
      icon: 'none'
    });
    return;
  }
  
  // 设置加载状态
  loading.value = true;
  
  // 调用登录方法
  handleWxLogin()
    .then((res: any) => {
      loading.value = false;
      
      // 登录成功后，触发主题色刷新事件
      setTimeout(() => {
        // 从缓存中获取主题色
        try {
          const userInfo = uni.getStorageSync('USER_INFO') || {};
          const avatarUrl = userInfo.avatarUrl;
          
          if (avatarUrl) {
            // 触发主题色刷新事件
            uni.$emit('refreshThemeColor');
            console.log('登录成功，触发主题色刷新事件');
          }
        } catch (error) {
          console.error('登录后刷新主题色失败:', error);
        }
      }, 500);
      
      // 获取存储的重定向路径
      const redirect = uni.getStorageSync('redirect');
      
      // 如果有存储的重定向路径，优先使用
      if (redirect) {
        uni.navigateTo({
          url: redirect,
          fail: (err: any) => {
            console.error('导航到重定向页面失败:', err);
            uni.redirectTo({
              url: redirect,
              fail: (redirectErr: any) => {
                console.error('重定向也失败:', redirectErr);
                // 如果重定向也失败，返回到"我的"页面
                uni.navigateTo({ url: ROUTES.USER });
              }
            });
          }
        });
        // 清除存储的重定向路径
        uni.removeStorageSync('redirect');
      } 
      // 如果是从"我的"页面来的，返回"我的"页面
      else if (fromPath.value === ROUTES.USER) {
        uni.navigateTo({
          url: ROUTES.USER,
          fail: (err: any) => {
            console.error('导航到"我的"页面失败:', err);
            uni.redirectTo({ url: ROUTES.USER });
          }
        });
      }
      // 默认跳转到首页
      else {
        uni.navigateTo({
          url: ROUTES.INDEX,
          fail: (err: any) => {
            console.error('导航到首页失败:', err);
            uni.redirectTo({ url: ROUTES.INDEX });
          }
        });
      }
    })
    .catch((err: any) => {
      loading.value = false;
      console.error('登录失败', err);
    });
};

// 跳转到协议页面
const goToAgreement = (type: string) => {
  uni.navigateTo({
    url: `${ROUTES.AGREEMENT}?type=${type}`
  });
};

// 页面加载时检查是否已登录
onLoad((options: any) => {
  // 获取页面参数
  if (options && options.from) {
    fromPath.value = decodeURIComponent(options.from);
    console.log('登录页面来源:', fromPath.value);
  }
  
  const pages = getCurrentPages();
  if (pages.length > 0) {
    const currentPage = pages[pages.length - 1] as any;
    if (currentPage && currentPage.options) {
      // 如果有redirect参数，保存到本地，登录成功后跳转
      if (currentPage.options.redirect) {
        uni.setStorageSync('redirect', decodeURIComponent(currentPage.options.redirect));
      }
      // 如果有from参数，记录来源页面
      if (currentPage.options.from && !fromPath.value) {
        fromPath.value = decodeURIComponent(currentPage.options.from);
        console.log('登录页面来源(从options):', fromPath.value);
      }
    }
  }
});
</script>

<style lang="scss">
.login-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 60rpx 40rpx;
  height: 100vh;
  background-color: #f8f8f8;
  
  .logo-box {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-top: 80rpx;
    
    .logo {
      width: 160rpx;
      height: 160rpx;
      border-radius: 20rpx;
    }
    
    .app-name {
      margin-top: 20rpx;
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
    }
  }
  
  .welcome-text {
    margin-top: 60rpx;
    text-align: center;
    
    .welcome-title {
      font-size: 40rpx;
      font-weight: bold;
      color: #333;
    }
    
    .welcome-desc {
      display: block;
      margin-top: 20rpx;
      font-size: 28rpx;
      color: #666;
    }
  }
  
  .login-box {
    width: 100%;
    margin-top: 100rpx;
    
    .login-btn {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 100%;
      height: 90rpx;
      background-color: #07c160;
      border-radius: 45rpx;
      font-size: 32rpx;
      color: #fff;
      
      .iconfont {
        margin-right: 10rpx;
        font-size: 36rpx;
      }
    }
    
    .agreement-box {
      display: flex;
      align-items: center;
      justify-content: center;
      margin-top: 30rpx;
      
      .agreement-text {
        font-size: 24rpx;
        color: #666;
        margin-left: 10rpx;
        
        .link {
          color: #07c160;
        }
      }
    }
  }
}
</style> 